package com.my_musc_service.service.impl;

/**
 * @author zhudunfeng
 * @date 2021/6/16 17:39
 */

import com.my_musc_service.dao.FavoriteDao;
import com.my_musc_service.dao.LogDao;
import com.my_musc_service.dao.SongDao;
import com.my_musc_service.dao.SonglistDao;
import com.my_musc_service.entity.*;
import com.my_musc_service.exception.CustomException;
import com.my_musc_service.interceptor.LoginInterceptor;
import com.my_musc_service.service.QueryService;
import com.my_musc_service.utils.DateUtils;
import lombok.Cleanup;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class QueryServiceImpl implements QueryService {

    @Autowired
    private SonglistDao songlistDao;

    @Autowired
    private SongDao songDao;

    @Autowired
    private FavoriteDao favoriteDao;

    @Autowired
    private LogDao logDao;


    @Value("${server.port}")
    private String port;

    //绑定文件上传路径到uploadPath
    @Value("${web.upload-path}")
    private String uploadPath;

    @Override
    public Map<String, Object> querySongOrList(QueryAllVO queryAllVO) {
        User userInfo = LoginInterceptor.getUserInfo();

        Integer total = new Integer(0);

        //判断songlist是否为null，非null在本歌单查询歌曲,否则，查询所有歌曲
        String type = queryAllVO.getType();
        Integer from = queryAllVO.getFrom();
        Integer size = queryAllVO.getSize();
        List<QueryResult> queryResultList = new ArrayList<>();
        if (StringUtils.isNotBlank(queryAllVO.getSongList())) {
            queryResultList = songlistDao.querySongBySongListId(String.valueOf(userInfo.getId()), queryAllVO.getSongList(), null, null, from, size);
            total = songlistDao.querySongCountBySongList(String.valueOf(userInfo.getId()), queryAllVO.getSongList(), null, null, from, size);
            if ("name".equals(type)) {
                queryResultList = songlistDao.querySongBySongListId(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , queryAllVO.getContent(), null, from, size);

                total = songlistDao.querySongCountBySongList(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , queryAllVO.getContent(), null, from, size);
            } else if ("singer".equals(type)) {
                queryResultList = songlistDao.querySongBySongListId(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , null, queryAllVO.getContent(), from, size);

                total = songlistDao.querySongCountBySongList(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , null, queryAllVO.getContent(), from, size);
            }
            //排序
            queryResultList.sort(Comparator.comparing(QueryResult::getSongIndex));
        } else {
            List<Song> songList = songDao.queryAllByLimit(from, size);
            List<Song> songs = songDao.queryAll(null);
            total = songs.size();
            queryResultList = songList.stream().map(song -> {
                QueryResult queryResult = new QueryResult();
                queryResult.setSongId(String.valueOf(song.getId()));
                queryResult.setName(song.getName());
                queryResult.setLyric(song.getLyric());
                queryResult.setSrc(song.getUrl());
                queryResult.setSinger(song.getSinger());
                queryResult.setCoverUrl(song.getCoverUrl());
                return queryResult;
            }).collect(Collectors.toList());
            if ("name".equals(type)) {
                queryResultList = songDao.querySongBySongNameOrSinger(queryAllVO.getContent(), null, from, size);
                total = songDao.querySongCountBySongNameOrSinger(queryAllVO.getContent(), null, from, size);
            } else if ("singer".equals(type)) {
                queryResultList = songDao.querySongBySongNameOrSinger(null, queryAllVO.getContent(), from, size);
                total = songDao.querySongCountBySongNameOrSinger(null, queryAllVO.getContent(), from, size);
            }
        }

        Favorite favorite = new Favorite();
        favorite.setUserId(String.valueOf(userInfo.getId()));
        List<Favorite> favorites = favoriteDao.queryAll(favorite);
        List<String> favoriteSongIds = favorites.stream().map(favorite1 -> favorite1.getSongId()).collect(Collectors.toList());
        //判断是否是最爱的
        queryResultList.stream().forEach(queryResult -> {
            if (favoriteSongIds.contains(queryResult.getSongId())) {
                queryResult.setIsFavorite(true);
            } else {
                queryResult.setIsFavorite(false);
            }
        });

        Map<String, Object> map = new HashMap<>();
        map.put("result", queryResultList);
        map.put("total", total);

        if (StringUtils.isNotBlank(queryAllVO.getContent())) {
            //添加日志记录
            Log log = new Log();
            log.setSearchHistory(queryAllVO.getContent());
            log.setUserId(userInfo.getId());
            log.setCreateTime(DateUtils.getNowDate());
            logDao.insert(log);
        }

        return map;
    }


    @Override
    public Map<String, Object> querySongOrListLike(QueryAllVO queryAllVO) {
        User userInfo = LoginInterceptor.getUserInfo();

        Integer total = new Integer(0);

        //判断songlist是否为null，非null在本歌单查询歌曲,否则，查询所有歌曲
        String type = queryAllVO.getType();
        Integer from = queryAllVO.getFrom();
        Integer size = queryAllVO.getSize();
        List<QueryResult> queryResultList = new ArrayList<>();
        if (StringUtils.isNotBlank(queryAllVO.getSongList())) {
            queryResultList = songlistDao.querySongBySongListIdLike(String.valueOf(userInfo.getId()), queryAllVO.getSongList(), null, null, from, size);
            total = songlistDao.querySongCountBySongListLike(String.valueOf(userInfo.getId()), queryAllVO.getSongList(), null, null, from, size);
            if ("name".equals(type)) {
                queryResultList = songlistDao.querySongBySongListIdLike(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , queryAllVO.getContent(), null, from, size);

                total = songlistDao.querySongCountBySongListLike(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , queryAllVO.getContent(), null, from, size);
            } else if ("singer".equals(type)) {
                queryResultList = songlistDao.querySongBySongListIdLike(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , null, queryAllVO.getContent(), from, size);

                total = songlistDao.querySongCountBySongListLike(String.valueOf(userInfo.getId()), queryAllVO.getSongList()
                        , null, queryAllVO.getContent(), from, size);
            }
            //排序
            queryResultList.sort(Comparator.comparing(QueryResult::getSongIndex));
        } else {
            List<Song> songList = songDao.queryAllByLimit(from, size);
            List<Song> songs = songDao.queryAll(null);
            total = songs.size();
            queryResultList = songList.stream().map(song -> {
                QueryResult queryResult = new QueryResult();
                queryResult.setSongId(String.valueOf(song.getId()));
                queryResult.setName(song.getName());
                queryResult.setLyric(song.getLyric());
                queryResult.setSrc(song.getUrl());
                queryResult.setSinger(song.getSinger());
                queryResult.setCoverUrl(song.getCoverUrl());
                return queryResult;
            }).collect(Collectors.toList());

            List<QueryResult> songNameList = songDao.querySongBySongNameOrSingerLike(queryAllVO.getContent(), null, from, size);
            //Integer integer = songDao.querySongCountBySongNameOrSingerLike(queryAllVO.getContent(), null, from, size);
            List<QueryResult> singerList = songDao.querySongBySongNameOrSingerLike(null, queryAllVO.getContent(), from, size);
            //Integer integer1 = songDao.querySongCountBySongNameOrSingerLike(null, queryAllVO.getContent(), from, size);
            queryResultList.clear();
            queryResultList.addAll(songNameList);
            queryResultList.addAll(singerList);
            queryResultList = queryResultList.stream().distinct().collect(Collectors.toList());
            total = queryResultList.size();
        }

        Favorite favorite = new Favorite();
        favorite.setUserId(String.valueOf(userInfo.getId()));
        List<Favorite> favorites = favoriteDao.queryAll(favorite);
        List<String> favoriteSongIds = favorites.stream().map(favorite1 -> favorite1.getSongId()).collect(Collectors.toList());
        //判断是否是最爱的
        queryResultList.stream().forEach(queryResult -> {
            if (favoriteSongIds.contains(queryResult.getSongId())) {
                queryResult.setIsFavorite(true);
            } else {
                queryResult.setIsFavorite(false);
            }
        });

        Map<String, Object> map = new HashMap<>();
        map.put("result", queryResultList);
        map.put("total", total);

        return map;
    }


    @Override
    public String queryLyricByUrl(String url) {
        if (StringUtils.isBlank(url)) {
            throw new CustomException("url为null或空串");
        }
        StringBuffer stringBuffer = new StringBuffer();

        String oriNameOne = url.substring(url.indexOf(port));
        String fileName = null;
        //兼容
        if (oriNameOne.contains("music")) {
            fileName = oriNameOne.substring(oriNameOne.lastIndexOf("music") + 6);
        } else {
            fileName = oriNameOne.substring(oriNameOne.indexOf("/") + 1);
        }
        String fileURI = uploadPath + fileName;
        File file = new File(fileURI);
        if (file.exists()) {
            try {
                @Cleanup FileInputStream fileInputStream = new FileInputStream(file);
                @Cleanup Reader reader = new InputStreamReader(fileInputStream, Charset.defaultCharset());
                // 输出资源内容到相应对象
                int len;
                while ((len = reader.read()) != -1) {
                    if (((char) len) != '\r') {
                        stringBuffer.append((char) len);
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            throw new CustomException("歌词文件不存在");
        }
        return stringBuffer.toString();
    }
}
